package edu.ntu.cloudroid.model.function.stats;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import edu.ntu.cloudroid.model.data.AbstractData;
import edu.ntu.cloudroid.model.data.DetachedData;
import edu.ntu.cloudroid.model.data.LocationData;

/**
 * @author anhdinh
 * Return the data appear most frequently in the list
 */
public class MostFrequentLocFunction implements IDataStats{

	//check for most frequent location. 
	@Override
	public Object getStats(List<AbstractData> data, Object params) {
		if (data==null || data.size()==0)
			return null;
		
		Map<LocObj,Integer> locSet = new HashMap<LocObj,Integer>();
		LocationData ld;
		LocObj lo;
		int maxCount=0;
		LocationData maxLoc=null;
		int val =0;
		for (AbstractData ad : data){
			ld = (LocationData)ad;
			lo = new LocObj(ld.getLongitude(), ld.getLatitude());
			if (!locSet.containsKey(lo)){
				locSet.put(lo, 1);
				val = 1;
			}
			else{
				val = locSet.get(lo).intValue()+1;
				locSet.remove(lo);
				locSet.put(lo, val);
			}
			if (val>maxCount){
				maxCount = val;
				maxLoc = ld;
			}
		}
		return maxLoc;
	}
	
}

class LocObj{
	double longt, latt;
	
	public LocObj(double lo, double lat){
		this.longt = lo;
		this.latt = lat;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		long temp;
		temp = Double.doubleToLongBits(latt);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		temp = Double.doubleToLongBits(longt);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		LocObj other = (LocObj) obj;
		return Math.abs(this.longt - other.longt) < 0.00001
				&& Math.abs(this.latt - other.latt) < 0.00001;			
	}
	
}